package com.bookshop.dao.impl;

import com.bookshop.dao.BaseDao;
import com.bookshop.dao.BookDao;
import com.bookshop.entity.Book;
import com.bookshop.entity.Category;
import com.bookshop.entity.Publisher;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 图书DAO实现
 */
public class BookDaoImpl extends BaseDao implements BookDao {
    @Override
    public List<Book> findBooksByCount(int limit) throws SQLException {
        String sql = "SELECT id,title,isbn FROM `books` where isSale = 1 order by clicks LIMIT ?";
        List<Book> books = new ArrayList<>();
        ResultSet rs = this.query(sql, limit);//调用查询方法
        while (rs.next()) {
            Book book = new Book();
            book.setId(rs.getInt("id"));
            book.setTitle(rs.getString("title"));
            book.setIsbn(rs.getString("isbn"));
            books.add(book);//循环添加图书到集合
        }
        this.closeAll(conn,null,rs);//关闭资源
        return books;
    }

    @Override
    public Book findById(int id) throws SQLException {
        Book book=null;
        String sql="SELECT b.id,b.title,b.author,b.ISBN,b.UnitPrice,b.PublishDate,b.TOC,b.ContentDescription,b.Clicks,b.saleTime,b.IsSale,b.sumStock,b.warnStock,c.id as cId,c.`name` as cName,p.id as pId,p.`name` as pName FROM `books` b \n" +
                "inner join categorie c on (b.CategoryId=c.id)\n" +
                "inner join publisher p on (b.PublisherId=p.id)\n" +
                "where b.id=?";
        ResultSet rs = this.query(sql, id);
        if (rs.next()) {
             book = new Book();// 创建图书对象
            book.setId(rs.getInt("id"));// 图书编号
            book.setTitle(rs.getString("title"));// 标题
            book.setIsbn(rs.getString("isbn"));// 图片名称
            book.setToc(rs.getString("toc"));// 章节
            book.setClicks(rs.getInt("clicks"));// 点击量
            book.setAuthor(rs.getString("author"));// 作者
            book.setUnitPrice(rs.getDouble("unitPrice"));// 价格
            book.setPublishDate(rs.getDate("publishDate"));// 出版日期
            book.setContentDescription(rs.getString("contentDescription"));// 内容简介
            book.setIsSale(rs.getInt("isSale"));// 上下架
            book.setSumStock(rs.getInt("sumStock"));// 总库存
            book.setSaleTime(rs.getDate("saleTime"));// 上架时间
            book.setWarnStock(rs.getInt("warnStock"));// 预警库存

            book.setCategory(new Category(rs.getInt("cId"),rs.getString("cName")));
            book.setPublisher(new Publisher(rs.getInt("pId"),rs.getString("pName")));

            this.closeAll(conn,null,rs);
            return  book;

        }


        return null;
    }
}
